#!/bin/bash

# 解析命令行参数
usage() {
    echo "用法: $0 [选项]"
    echo "选项:"
    echo "  -p, --path PATH    指定安装路径前缀 (比如: ./install.sh -p /usr/local/bin)"
    echo "  -h, --help         显示此帮助信息"
    exit 1
}

# 默认安装路径
CUSTOM_INSTALL_PATH=""

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
        -p|--path)
            CUSTOM_INSTALL_PATH="$2"
            shift 2
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo "未知选项: $1"
            usage
            ;;
    esac
done

# 导出安装路径环境变量，供config.sh使用
export CUSTOM_INSTALL_PATH

# 检查是否提供了安装路径
if [ -z "$CUSTOM_INSTALL_PATH" ]; then
    echo "错误: 必须指定安装路径"
    usage
fi

# 定义颜色
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 打印带颜色的信息
info() {
    echo "[信息] \$1"
}

warn() {
    echo "[警告] \$1"
}

error() {
    echo "[错误] \$1"
}

# 检查是否以root权限运行
check_root() {
    if [ "$EUID" -ne 0 ]; then
        error "请使用root权限运行此脚本"
    fi
}

# 加载配置
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
CURRENT_DIR="$( pwd )"

# 尝试从不同位置加载config.sh
if [ -f "${SCRIPT_DIR}/service/config.sh" ]; then
    source "${SCRIPT_DIR}/service/config.sh"
elif [ -f "${CURRENT_DIR}/service/config.sh" ]; then
    source "${CURRENT_DIR}/service/config.sh"
elif [ -f "${SCRIPT_DIR}/../micro/config.sh" ]; then
    source "${SCRIPT_DIR}/../micro/config.sh"
else
    echo "错误: 找不到config.sh文件"
    exit 1
fi

# 显示安装信息
info "安装路径: ${INSTALL_FULL_PATH}"

# 设置备份相关变量
DATETIME=$(date +%Y%m%d_%H%M%S)
BACKUP_ROOT="${INSTALL_PATH}/fdsmastergo_backup"
BACKUP_FILE="${BACKUP_ROOT}/${SOFTWARE_NAME}_${DATETIME}.tar.gz"

# 检查权限
check_root

# 提示用户安装影响
echo -e "${YELLOW}警告：${NC}"
echo "1. 安装过程将会停止所有 ${SOFTWARE_NAME} 服务"
echo "2. 安装过程预计需要 1-3 分钟"
echo "3. 旧版本将被备份到 ${BACKUP_FILE}"
echo -e "${YELLOW}是否继续？[y/N]${NC}"
read -r response
if [[ ! "$response" =~ ^[yY]$ ]]; then
    echo "安装已取消"
    exit 0
fi

# 停止现有服务
info "停止现有服务..."
if [ -f "/etc/init.d/fdsmastergo" ]; then
    /etc/init.d/fdsmastergo stop
elif [ -f "${INSTALL_FULL_PATH}/service/micro_stop.sh" ]; then
    "${INSTALL_FULL_PATH}/service/micro_stop.sh"
else
    warn "未找到停止脚本，尝试直接终止进程..."
    if [ -f "${INSTALL_FULL_PATH}/services.json" ]; then
        SERVICES=$(jq -r '.start_order[]' "${INSTALL_FULL_PATH}/services.json" 2>/dev/null)
        for service in $SERVICES; do
            pkill -x "$service" >/dev/null 2>&1 || true
            sleep 1
        done
    fi
fi

# 检查磁盘空间
FREE_SPACE=$(df -k "${INSTALL_PATH}" | awk 'NR==2 {print $4}')
if [ -n "$FREE_SPACE" ] && [ "$FREE_SPACE" -lt 10240 ]; then
    error "磁盘空间不足，至少需要10MB可用空间。当前可用空间: $(($FREE_SPACE/1024))MB"
fi

# 备份和清理
if [ -d "${INSTALL_FULL_PATH}" ]; then
    # 创建备份目录
    mkdir -p "${BACKUP_ROOT}" || warn "无法创建备份目录: ${BACKUP_ROOT}"
    
    warn "备份旧版本到 ${BACKUP_FILE}..."
    # 备份（使用tar压缩）
    tar -czf "${BACKUP_FILE}" -C "$(dirname "${INSTALL_FULL_PATH}")" "$(basename "${INSTALL_FULL_PATH}")" || warn "备份失败，继续安装"
    # 清理旧版本
    info "清理旧版本..."
    rm -rf "${INSTALL_FULL_PATH}" || warn "清理旧版本失败"
else
    # 创建新目录
    mkdir -p "${INSTALL_FULL_PATH}" || error "创建目录失败: ${INSTALL_FULL_PATH}"
fi

# 创建目标目录
info "开始安装 ${SOFTWARE_NAME}..."

# 获取当前目录（应该是fdsmastergo_install目录）
CURRENT_DIR="$( pwd )"

# 复制文件
info "正在复制文件..."
info "源目录: ${CURRENT_DIR}"
info "目标目录: ${INSTALL_FULL_PATH}"

# 创建必要的目录
mkdir -p "${INSTALL_FULL_PATH}/cmd" || error "创建cmd目录失败"
mkdir -p "${INSTALL_FULL_PATH}/service" || error "创建service目录失败"
mkdir -p "${INSTALL_FULL_PATH}/cmd/logs" || error "创建日志目录失败"

info "复制可执行文件..."
cp -r "${CURRENT_DIR}/cmd" "${INSTALL_FULL_PATH}/" || error "复制可执行文件失败"
info "复制服务脚本..."
cp -r "${CURRENT_DIR}/service" "${INSTALL_FULL_PATH}/" || error "复制服务脚本失败"
info "复制卸载脚本..."
cp "${CURRENT_DIR}/uninstall.sh" "${INSTALL_FULL_PATH}/" || error "复制卸载脚本失败"
info "复制说明文档..."
cp "${CURRENT_DIR}/README.md" "${INSTALL_FULL_PATH}/" || error "复制说明文档失败"
info "复制配置文件..."
cp "${CURRENT_DIR}/services.json" "${INSTALL_FULL_PATH}/" || error "复制配置文件失败"

# 设置权限
info "设置文件权限..."
chmod -R 755 "${INSTALL_FULL_PATH}/cmd" || warn "设置cmd目录权限失败"
chmod -R 755 "${INSTALL_FULL_PATH}/service" || warn "设置service目录权限失败"
chmod 644 "${INSTALL_FULL_PATH}/services.json" || warn "设置services.json权限失败"
chmod 755 "${INSTALL_FULL_PATH}/uninstall.sh" || warn "设置uninstall.sh权限失败"
chmod 644 "${INSTALL_FULL_PATH}/README.md" || warn "设置README.md权限失败"

# 安装SysVinit服务脚本
info "安装SysVinit服务脚本..."

# 使用fdsmastergo作为服务脚本
# 服务脚本应该位于service目录下
SERVICE_SCRIPT="${CURRENT_DIR}/service/fdsmastergo"
if [ ! -f "${SERVICE_SCRIPT}" ]; then
    error "未找到服务脚本: ${SERVICE_SCRIPT}"
    info "当前目录: $(pwd)"
    info "安装包目录: ${CURRENT_DIR}"
    info "目录内容: $(ls -l ${CURRENT_DIR}/service 2>/dev/null || echo '目录不存在')"
    exit 1
fi

# 创建临时服务脚本
TMP_SERVICE_FILE="/tmp/fdsmastergo.tmp"
cp "${SERVICE_SCRIPT}" "${TMP_SERVICE_FILE}" || error "复制服务脚本失败"

# 替换安装路径 - 确保使用正确的安装路径
info "设置服务脚本中的安装路径: ${INSTALL_FULL_PATH}"
sed -i "s|__INSTALL_FULL_PATH__|${INSTALL_FULL_PATH}|g" "${TMP_SERVICE_FILE}" || warn "替换安装路径失败"

# 确保脚本使用Unix格式的行尾
info "确保服务脚本使用Unix格式的行尾"
if command -v dos2unix >/dev/null 2>&1; then
    dos2unix "${TMP_SERVICE_FILE}" || warn "转换行尾格式失败"
else
    # 如果没有dos2unix命令，使用tr命令替代
    TMP_FILE2="/tmp/fdsmastergo.unix"
    tr -d '\r' < "${TMP_SERVICE_FILE}" > "${TMP_FILE2}" && mv "${TMP_FILE2}" "${TMP_SERVICE_FILE}" || warn "转换行尾格式失败"
fi

# 复制修改后的服务脚本
cp "${TMP_SERVICE_FILE}" "/etc/init.d/fdsmastergo" || error "复制服务脚本到/etc/init.d失败"
chmod 755 "/etc/init.d/fdsmastergo" || error "设置服务脚本权限失败"

# 添加开机启动
if command -v update-rc.d >/dev/null 2>&1; then
    update-rc.d fdsmastergo defaults || warn "设置开机启动失败(update-rc.d)"
elif command -v chkconfig >/dev/null 2>&1; then
    chkconfig --add fdsmastergo || warn "设置开机启动失败(chkconfig)"
else
    # Buildroot通常使用简单的符号链接方式
    for i in 2 3 4 5; do
        ln -sf /etc/init.d/fdsmastergo /etc/rc${i}.d/S90fdsmastergo 2>/dev/null || true
    done
    for i in 0 1 6; do
        ln -sf /etc/init.d/fdsmastergo /etc/rc${i}.d/K10fdsmastergo 2>/dev/null || true
    done
    info "已使用符号链接方式设置开机启动"
fi

# 清理临时文件
rm -f "${TMP_SERVICE_FILE}"

info "SysVinit服务脚本安装成功"

# 启动服务
info "启动服务..."
/etc/init.d/fdsmastergo start || warn "服务启动失败"
status=$?

# 检查服务状态
info "检查服务状态..."
/etc/init.d/fdsmastergo status || warn "无法获取服务状态"

# 安装完成
echo
echo -e "${GREEN}安装完成！${NC}"
echo -e "${YELLOW}安装信息：${NC}"
echo -e "  安装路径：${INSTALL_FULL_PATH}"
echo -e "  备份文件：${BACKUP_FILE}"
echo -e "  可执行文件：${INSTALL_FULL_PATH}/cmd/*/bin/*"
echo -e "  配置文件：${INSTALL_FULL_PATH}/services.json"
echo -e "  服务脚本：/etc/init.d/fdsmastergo"
echo
echo -e "${YELLOW}使用说明：${NC}"
echo -e "  1. 服务管理："
echo -e "     - 启动服务：/etc/init.d/fdsmastergo start"
echo -e "     - 停止服务：/etc/init.d/fdsmastergo stop"
echo -e "     - 重启服务：/etc/init.d/fdsmastergo restart"
echo -e "     - 查看状态：/etc/init.d/fdsmastergo status"
echo -e "  2. 查看日志："
echo -e "     - 日志目录：${INSTALL_FULL_PATH}/cmd/logs"
echo

echo -e "${YELLOW}卸载说明：${NC}"
echo -e "  1. 如需卸载，请执行："
echo -e "     cd ${INSTALL_FULL_PATH} && ./uninstall.sh"
echo -e "  2. 重要提示："
echo -e "     - 不同版本的卸载脚本可能不兼容，安装和卸载程序的版本要一致"
echo -e "     - 禁止使用新版本的卸载脚本来卸载旧版本程序"
echo

echo -e "${YELLOW}备份说明：${NC}"
echo -e "  1. 旧版本已备份到：${BACKUP_FILE}"
echo -e "  2. 如需回滚，请按以下步骤操作："
echo -e "     a) 停止当前服务：/etc/init.d/fdsmastergo stop"
echo -e "     b) 删除当前安装：rm -rf ${INSTALL_FULL_PATH}/*"
echo -e "     c) 解压备份文件：tar -xzf ${BACKUP_FILE} -C $(dirname "${INSTALL_FULL_PATH}")"
echo -e "     d) 启动服务：/etc/init.d/fdsmastergo start"
echo
echo -e "${GREEN}祝您使用愉快！${NC}"

echo -e "${YELLOW}相关信息也可参考 ${INSTALL_FULL_PATH}/README.md ${NC}"

exit $status 